package com.ruoyi.caigou.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.basedata.api.RemoteGoodsService;
import com.ruoyi.caigou.domain.dto.BuyReqDTO;
import com.ruoyi.caigou.domain.dto.IdAndNumber;
import com.ruoyi.caigou.domain.pojo.BuyReqGoods;
import com.ruoyi.caigou.mapper.BuyReqGoodsMapper;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.system.api.domain.basedata.Goods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.caigou.mapper.BuyReqMapper;
import com.ruoyi.caigou.domain.BuyReq;
import com.ruoyi.caigou.service.IBuyReqService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采购申请Service业务层处理
 * 
 * @author lvql
 * @date 2024-10-25
 */
@Slf4j
@Service
public class BuyReqServiceImpl implements IBuyReqService 
{
    @Autowired
    private BuyReqMapper buyReqMapper;

    @Autowired
    private BuyReqGoodsMapper buyReqGoodsMapper;

    @Autowired
    private RemoteGoodsService remoteGoodsService;
    /**
     * 查询采购申请
     * 
     * @param id 采购申请主键
     * @return 采购申请
     */
    @Override
    public BuyReq selectBuyReqById(Integer id)
    {
        return buyReqMapper.selectBuyReqById(id);
    }

    @Override
    public BuyReqDTO selectBuyReqByIdPlus(Integer id) {
        BuyReq buyReq = this.selectBuyReqById(id);

        List<BuyReqGoods> buyReqGoodsList = buyReqGoodsMapper.selectBuyReqGoodsByBuyReqCode(buyReq.getCode());
        List<Integer> ids = new ArrayList<>();
        for (BuyReqGoods buyReqGoods : buyReqGoodsList) {
            ids.add(buyReqGoods.getGoodsId());
        }
        R<List<Goods>> goodsListByIds = R.ok();
        if (!ids.isEmpty()){
            goodsListByIds = remoteGoodsService.getGoodsListByIds(ids, SecurityConstants.INNER);
        }
        if (R.FAIL == goodsListByIds.getCode())
        {
            throw new ServiceException(goodsListByIds.getMsg());
        }
        log.info("selectBuyReqByIdPlus goodsListByIds params {}", goodsListByIds);
        BuyReqDTO buyReqDTO = new BuyReqDTO();
        buyReqDTO.setBuyReqDataBase(buyReq);
        buyReqDTO.setGoodsList(goodsListByIds.getData());

        List<IdAndNumber> idAndNumberList = new ArrayList<>();
        for (BuyReqGoods buyReqGoods : buyReqGoodsList) {
            idAndNumberList.add(new IdAndNumber(buyReqGoods.getGoodsId(), buyReqGoods.getGoodsNumber()));
        }

        buyReqDTO.setIdAndNumberList(idAndNumberList);
        return buyReqDTO;
    }

    @Override
    public BuyReqDTO selectBuyReqByCodePlus(String sourceCode) {
        BuyReq buyReq = buyReqMapper.selectBuyReqByCode(sourceCode);
        if (buyReq==null){
            throw new ServiceException("buyReq is null");
        }
        return selectBuyReqByIdPlus(buyReq.getId());
    }

    /**
     * 查询采购申请列表
     * 
     * @param buyReq 采购申请
     * @return 采购申请
     */
    @Override
    public List<BuyReq> selectBuyReqList(BuyReq buyReq)
    {
        return buyReqMapper.selectBuyReqList(buyReq);
    }

    /**
     * 新增采购申请
     * 
     * @param buyReq 采购申请
     * @return 结果
     */
    @Override
    public int insertBuyReq(BuyReq buyReq)
    {
        return buyReqMapper.insertBuyReq(buyReq);
    }


    @Transactional
    @Override
    public int insertBuyReqPlus(BuyReqDTO buyReqDTO) {
        BuyReq buyReqDataBase = buyReqDTO.getBuyReqDataBase();
//        insertBuyReq(buyReqDataBase);
        List<IdAndNumber> idAndNumberList = buyReqDTO.getIdAndNumberList();

        List<BuyReqGoods> goodsList = new ArrayList<>();
        for (IdAndNumber idAndNumber : idAndNumberList) {

            BuyReqGoods buyReqGoods = new BuyReqGoods();
            buyReqGoods.setBuyReqCode(buyReqDataBase.getCode());
            buyReqGoods.setGoodsId(idAndNumber.getId());
            buyReqGoods.setGoodsNumber(idAndNumber.getNumber());
            goodsList.add(buyReqGoods);
        }

        buyReqMapper.insertBuyReq(buyReqDataBase);
        return buyReqGoodsMapper.insertBuyReqGoodsList(merge(goodsList));
    }
    /**
     * 将id相同进行合并 number 相加道回合并后的集合使用Java8的流进行处理
     */
    public List<BuyReqGoods> merge(List<BuyReqGoods> list) {
        List<BuyReqGoods> result = list.stream()
                // 表示id为key， 接着如果有重复的，那么从BuyReqGoods对象o1与o2中筛选出一个，这里选择o1，
                // 并把id重复，需要将number和number与o1进行合并的o2, 赋值给o1，最后返回o1
                .collect(Collectors.toMap(BuyReqGoods::getGoodsId, a -> a, (o1, o2)-> {
                    o1.setId(o1.getGoodsId());
                    o1.setBuyReqCode(o1.getBuyReqCode());
                    o1.setGoodsNumber(o1.getGoodsNumber() + o2.getGoodsNumber());
                    return o1;
                })).values().stream().collect(Collectors.toList());
        return result ;
    }


    /**
     * 修改采购申请
     * 
     * @param buyReq 采购申请
     * @return 结果
     */
    @Override
    public int updateBuyReq(BuyReq buyReq)
    {
        return buyReqMapper.updateBuyReq(buyReq);
    }

    @Transactional
    @Override
    public int updateBuyReqPlus(BuyReqDTO buyReqDTO) {

        String code = buyReqDTO.getBuyReqDataBase().getCode();

        buyReqGoodsMapper.deleteBuyReqGoodsByBuyReqCode(code);

        buyReqMapper.deleteBuyReqById(buyReqDTO.getBuyReqDataBase().getId());
        return insertBuyReqPlus(buyReqDTO);
    }

    /**
     * 批量删除采购申请
     * 
     * @param ids 需要删除的采购申请主键
     * @return 结果
     */
    @Override
    public int deleteBuyReqByIds(Integer[] ids)
    {
        return buyReqMapper.deleteBuyReqByIds(ids);
    }

    /**
     * 删除采购申请信息
     * 
     * @param id 采购申请主键
     * @return 结果
     */
    @Override
    public int deleteBuyReqById(Integer id)
    {
        return buyReqMapper.deleteBuyReqById(id);
    }

    @Transactional
    @Override
    public int deleteBuyReqByIdsPlus(Integer[] ids) {

        for (int i = 0; i < ids.length; i++) {
            BuyReq buyReq = buyReqMapper.selectBuyReqById(ids[i]);
            buyReqGoodsMapper.deleteBuyReqGoodsByBuyReqCode(buyReq.getCode());
        }
        return deleteBuyReqByIds(ids);
    }
}
